﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Dapper;
using DapperExtensions;
using MaximServices.Common;
using MaximServices.Data;
using MaximServices.Model;
using Microsoft.Extensions.Options;
using MySql.Data.MySqlClient;

namespace MaximServices.Repository
{
    public class MottoBaikeRepository
    {
        private readonly DataBaseRepository _dbrsp;

        public MottoBaikeRepository(DataBaseRepository dbrsp)
        {
            _dbrsp = dbrsp;
        }

        public void Dispose()
        {
            _dbrsp.Database.Dispose();
        }

        public MottoBaike FindBaikeLogFromMottoId(string mottoId)
        {
            var predicate = Predicates.Field<MottoBaike>(f => f.MottoId, Operator.Eq, mottoId);

            return _dbrsp.Database.GetList<MottoBaike>(predicate, null, null, false).FirstOrDefault();
        }

        /// <summary>
        /// 保存百科信息
        /// </summary>
        /// <param name="mottoBaike"></param>
        /// <param name="motto"></param>
        public void SaveBaikeInfo(MottoBaike mottoBaike, Motto motto)
        {
            _dbrsp.Database.BeginTransaction();

            try
            {
                if (string.IsNullOrWhiteSpace(mottoBaike.Id))
                {
                    mottoBaike.Id = IdFactory.NextId;
                    _dbrsp.Database.Insert(mottoBaike, null);
                }
                else
                {
                    _dbrsp.Database.Update(mottoBaike, null);
                }

                _dbrsp.Database.Update(motto, null);

                _dbrsp.Database.Commit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("SaveBaikeInfo : " + ex);

                _dbrsp.Database.Rollback();
            }
        }
    }
}
